home *** CD-ROM | disk | FTP | other *** search
/ Komputer for Alle 2004 #2 / K-CD-2-2004.ISO / OpenOffice Sv / f_0397 / python-core-2.2.2 / lib / test / test_long.py < prev    next >
Encoding:
Python Source  |  2003-07-18  |  13.1 KB  |  409 lines

  1. from test_support import verify, verbose, TestFailed, fcmp
  2. from string import join
  3. from random import random, randint
  4.  
  5. # SHIFT should match the value in longintrepr.h for best testing.
  6. SHIFT = 15
  7. BASE = 2 ** SHIFT
  8. MASK = BASE - 1
  9.  
  10. # Max number of base BASE digits to use in test cases.  Doubling
  11. # this will at least quadruple the runtime.
  12. MAXDIGITS = 10
  13.  
  14. # build some special values
  15. special = map(long, [0, 1, 2, BASE, BASE >> 1])
  16. special.append(0x5555555555555555L)
  17. special.append(0xaaaaaaaaaaaaaaaaL)
  18. #  some solid strings of one bits
  19. p2 = 4L  # 0 and 1 already added
  20. for i in range(2*SHIFT):
  21.     special.append(p2 - 1)
  22.     p2 = p2 << 1
  23. del p2
  24. # add complements & negations
  25. special = special + map(lambda x: ~x, special) + \
  26.                     map(lambda x: -x, special)
  27.  
  28. # ------------------------------------------------------------ utilities
  29.  
  30. # Use check instead of assert so the test still does something
  31. # under -O.
  32.  
  33. def check(ok, *args):
  34.     if not ok:
  35.         raise TestFailed, join(map(str, args), " ")
  36.  
  37. # Get quasi-random long consisting of ndigits digits (in base BASE).
  38. # quasi == the most-significant digit will not be 0, and the number
  39. # is constructed to contain long strings of 0 and 1 bits.  These are
  40. # more likely than random bits to provoke digit-boundary errors.
  41. # The sign of the number is also random.
  42.  
  43. def getran(ndigits):
  44.     verify(ndigits > 0)
  45.     nbits_hi = ndigits * SHIFT
  46.     nbits_lo = nbits_hi - SHIFT + 1
  47.     answer = 0L
  48.     nbits = 0
  49.     r = int(random() * (SHIFT * 2)) | 1  # force 1 bits to start
  50.     while nbits < nbits_lo:
  51.         bits = (r >> 1) + 1
  52.         bits = min(bits, nbits_hi - nbits)
  53.         verify(1 <= bits <= SHIFT)
  54.         nbits = nbits + bits
  55.         answer = answer << bits
  56.         if r & 1:
  57.             answer = answer | ((1 << bits) - 1)
  58.         r = int(random() * (SHIFT * 2))
  59.     verify(nbits_lo <= nbits <= nbits_hi)
  60.     if random() < 0.5:
  61.         answer = -answer
  62.     return answer
  63.  
  64. # Get random long consisting of ndigits random digits (relative to base
  65. # BASE).  The sign bit is also random.
  66.  
  67. def getran2(ndigits):
  68.     answer = 0L
  69.     for i in range(ndigits):
  70.         answer = (answer << SHIFT) | randint(0, MASK)
  71.     if random() < 0.5:
  72.         answer = -answer
  73.     return answer
  74.  
  75. # --------------------------------------------------------------- divmod
  76.  
  77. def test_division_2(x, y):
  78.     q, r = divmod(x, y)
  79.     q2, r2 = x//y, x%y
  80.     pab, pba = x*y, y*x
  81.     check(pab == pba, "multiplication does not commute for", x, y)
  82.     check(q == q2, "divmod returns different quotient than / for", x, y)
  83.     check(r == r2, "divmod returns different mod than % for", x, y)
  84.     check(x == q*y + r, "x != q*y + r after divmod on", x, y)
  85.     if y > 0:
  86.         check(0 <= r < y, "bad mod from divmod on", x, y)
  87.     else:
  88.         check(y < r <= 0, "bad mod from divmod on", x, y)
  89.  
  90. def test_division(maxdigits=MAXDIGITS):
  91.     if verbose:
  92.         print "long / * % divmod"
  93.     digits = range(1, maxdigits+1)
  94.     for lenx in digits:
  95.         x = getran(lenx)
  96.         for leny in digits:
  97.             y = getran(leny) or 1L
  98.             test_division_2(x, y)
  99.  
  100. # -------------------------------------------------------------- ~ & | ^
  101.  
  102. def test_bitop_identities_1(x):
  103.     check(x & 0 == 0, "x & 0 != 0 for", x)
  104.     check(x | 0 == x, "x | 0 != x for", x)
  105.     check(x ^ 0 == x, "x ^ 0 != x for", x)
  106.     check(x & -1 == x, "x & -1 != x for", x)
  107.     check(x | -1 == -1, "x | -1 != -1 for", x)
  108.     check(x ^ -1 == ~x, "x ^ -1 != ~x for", x)
  109.     check(x == ~~x, "x != ~~x for", x)
  110.     check(x & x == x, "x & x != x for", x)
  111.     check(x | x == x, "x | x != x for", x)
  112.     check(x ^ x == 0, "x ^ x != 0 for", x)
  113.     check(x & ~x == 0, "x & ~x != 0 for", x)
  114.     check(x | ~x == -1, "x | ~x != -1 for", x)
  115.     check(x ^ ~x == -1, "x ^ ~x != -1 for", x)
  116.     check(-x == 1 + ~x == ~(x-1), "not -x == 1 + ~x == ~(x-1) for", x)
  117.     for n in range(2*SHIFT):
  118.         p2 = 2L ** n
  119.         check(x << n >> n == x, "x << n >> n != x for", x, n)
  120.         check(x // p2 == x >> n, "x // p2 != x >> n for x n p2", x, n, p2)
  121.         check(x * p2 == x << n, "x * p2 != x << n for x n p2", x, n, p2)
  122.         check(x & -p2 == x >> n << n == x & ~(p2 - 1),
  123.             "not x & -p2 == x >> n << n == x & ~(p2 - 1) for x n p2",
  124.             x, n, p2)
  125.  
  126. def test_bitop_identities_2(x, y):
  127.     check(x & y == y & x, "x & y != y & x for", x, y)
  128.     check(x | y == y | x, "x | y != y | x for", x, y)
  129.     check(x ^ y == y ^ x, "x ^ y != y ^ x for", x, y)
  130.     check(x ^ y ^ x == y, "x ^ y ^ x != y for", x, y)
  131.     check(x & y == ~(~x | ~y), "x & y != ~(~x | ~y) for", x, y)
  132.     check(x | y == ~(~x & ~y), "x | y != ~(~x & ~y) for", x, y)
  133.     check(x ^ y == (x | y) & ~(x & y),
  134.          "x ^ y != (x | y) & ~(x & y) for", x, y)
  135.     check(x ^ y == (x & ~y) | (~x & y),
  136.          "x ^ y == (x & ~y) | (~x & y) for", x, y)
  137.     check(x ^ y == (x | y) & (~x | ~y),
  138.          "x ^ y == (x | y) & (~x | ~y) for", x, y)
  139.  
  140. def test_bitop_identities_3(x, y, z):
  141.     check((x & y) & z == x & (y & z),
  142.          "(x & y) & z != x & (y & z) for", x, y, z)
  143.     check((x | y) | z == x | (y | z),
  144.          "(x | y) | z != x | (y | z) for", x, y, z)
  145.     check((x ^ y) ^ z == x ^ (y ^ z),
  146.          "(x ^ y) ^ z != x ^ (y ^ z) for", x, y, z)
  147.     check(x & (y | z) == (x & y) | (x & z),
  148.          "x & (y | z) != (x & y) | (x & z) for", x, y, z)
  149.     check(x | (y & z) == (x | y) & (x | z),
  150.          "x | (y & z) != (x | y) & (x | z) for", x, y, z)
  151.  
  152. def test_bitop_identities(maxdigits=MAXDIGITS):
  153.     if verbose:
  154.         print "long bit-operation identities"
  155.     for x in special:
  156.         test_bitop_identities_1(x)
  157.     digits = range(1, maxdigits+1)
  158.     for lenx in digits:
  159.         x = getran(lenx)
  160.         test_bitop_identities_1(x)
  161.         for leny in digits:
  162.             y = getran(leny)
  163.             test_bitop_identities_2(x, y)
  164.             test_bitop_identities_3(x, y, getran((lenx + leny)//2))
  165.  
  166. # ------------------------------------------------- hex oct repr str atol
  167.  
  168. def slow_format(x, base):
  169.     if (x, base) == (0, 8):
  170.         # this is an oddball!
  171.         return "0L"
  172.     digits = []
  173.     sign = 0
  174.     if x < 0:
  175.         sign, x = 1, -x
  176.     while x:
  177.         x, r = divmod(x, base)
  178.         digits.append(int(r))
  179.     digits.reverse()
  180.     digits = digits or [0]
  181.     return '-'[:sign] + \
  182.            {8: '0', 10: '', 16: '0x'}[base] + \
  183.            join(map(lambda i: "0123456789ABCDEF"[i], digits), '') + \
  184.            "L"
  185.  
  186. def test_format_1(x):
  187.     from string import atol
  188.     for base, mapper in (8, oct), (10, repr), (16, hex):
  189.         got = mapper(x)
  190.         expected = slow_format(x, base)
  191.         check(got == expected, mapper.__name__, "returned",
  192.               got, "but expected", expected, "for", x)
  193.         check(atol(got, 0) == x, 'atol("%s", 0) !=' % got, x)
  194.     # str() has to be checked a little differently since there's no
  195.     # trailing "L"
  196.     got = str(x)
  197.     expected = slow_format(x, 10)[:-1]
  198.     check(got == expected, mapper.__name__, "returned",
  199.           got, "but expected", expected, "for", x)
  200.  
  201. def test_format(maxdigits=MAXDIGITS):
  202.     if verbose:
  203.         print "long str/hex/oct/atol"
  204.     for x in special:
  205.         test_format_1(x)
  206.     for i in range(10):
  207.         for lenx in range(1, maxdigits+1):
  208.             x = getran(lenx)
  209.             test_format_1(x)
  210.  
  211. # ----------------------------------------------------------------- misc
  212.  
  213. def test_misc(maxdigits=MAXDIGITS):
  214.     if verbose:
  215.         print "long miscellaneous operations"
  216.     import sys
  217.  
  218.     # check the extremes in int<->long conversion
  219.     hugepos = sys.maxint
  220.     hugeneg = -hugepos - 1
  221.     hugepos_aslong = long(hugepos)
  222.     hugeneg_aslong = long(hugeneg)
  223.     check(hugepos == hugepos_aslong, "long(sys.maxint) != sys.maxint")
  224.     check(hugeneg == hugeneg_aslong,
  225.         "long(-sys.maxint-1) != -sys.maxint-1")
  226.  
  227.     # long -> int should not fail for hugepos_aslong or hugeneg_aslong
  228.     try:
  229.         check(int(hugepos_aslong) == hugepos,
  230.               "converting sys.maxint to long and back to int fails")
  231.     except OverflowError:
  232.         raise TestFailed, "int(long(sys.maxint)) overflowed!"
  233.     try:
  234.         check(int(hugeneg_aslong) == hugeneg,
  235.               "converting -sys.maxint-1 to long and back to int fails")
  236.     except OverflowError:
  237.         raise TestFailed, "int(long(-sys.maxint-1)) overflowed!"
  238.  
  239.     # but long -> int should overflow for hugepos+1 and hugeneg-1
  240.     x = hugepos_aslong + 1
  241.     try:
  242.         int(x)
  243.         raise ValueError
  244.     except OverflowError:
  245.         pass
  246.     except:
  247.         raise TestFailed, "int(long(sys.maxint) + 1) didn't overflow"
  248.  
  249.     x = hugeneg_aslong - 1
  250.     try:
  251.         int(x)
  252.         raise ValueError
  253.     except OverflowError:
  254.         pass
  255.     except:
  256.         raise TestFailed, "int(long(-sys.maxint-1) - 1) didn't overflow"
  257.  
  258. # ----------------------------------- tests of auto int->long conversion
  259.  
  260. def test_auto_overflow():
  261.     import math, sys
  262.  
  263.     if verbose:
  264.         print "auto-convert int->long on overflow"
  265.  
  266.     special = [0, 1, 2, 3, sys.maxint-1, sys.maxint, sys.maxint+1]
  267.     sqrt = int(math.sqrt(sys.maxint))
  268.     special.extend([sqrt-1, sqrt, sqrt+1])
  269.     special.extend([-i for i in special])
  270.  
  271.     def checkit(*args):
  272.         # Heavy use of nested scopes here!
  273.         verify(got == expected, "for %r expected %r got %r" %
  274.                                 (args, expected, got))
  275.  
  276.     for x in special:
  277.         longx = long(x)
  278.  
  279.         expected = -longx
  280.         got = -x
  281.         checkit('-', x)
  282.  
  283.         for y in special:
  284.             longy = long(y)
  285.  
  286.             expected = longx + longy
  287.             got = x + y
  288.             checkit(x, '+', y)
  289.  
  290.             expected = longx - longy
  291.             got = x - y
  292.             checkit(x, '-', y)
  293.  
  294.             expected = longx * longy
  295.             got = x * y
  296.             checkit(x, '*', y)
  297.  
  298.             if y:
  299.                 expected = longx / longy
  300.                 got = x / y
  301.                 checkit(x, '/', y)
  302.  
  303.                 expected = longx // longy
  304.                 got = x // y
  305.                 checkit(x, '//', y)
  306.  
  307.                 expected = divmod(longx, longy)
  308.                 got = divmod(longx, longy)
  309.                 checkit(x, 'divmod', y)
  310.  
  311.             if abs(y) < 5 and not (x == 0 and y < 0):
  312.                 expected = longx ** longy
  313.                 got = x ** y
  314.                 checkit(x, '**', y)
  315.  
  316.                 for z in special:
  317.                     if z != 0 :
  318.                         if y >= 0:
  319.                             expected = pow(longx, longy, long(z))
  320.                             got = pow(x, y, z)
  321.                             checkit('pow', x, y, '%', z)
  322.                         else:
  323.                             try:
  324.                                 pow(longx, longy, long(z))
  325.                             except TypeError:
  326.                                 pass
  327.                             else:
  328.                                 raise TestFailed("pow%r should have raised "
  329.                                 "TypeError" % ((longx, longy, long(z))))
  330.  
  331. # ---------------------------------------- tests of long->float overflow
  332.  
  333. def test_float_overflow():
  334.     import math
  335.  
  336.     if verbose:
  337.         print "long->float overflow"
  338.  
  339.     for x in -2.0, -1.0, 0.0, 1.0, 2.0:
  340.         verify(float(long(x)) == x)
  341.  
  342.     huge = 1L << 30000
  343.     mhuge = -huge
  344.     namespace = {'huge': huge, 'mhuge': mhuge, 'math': math}
  345.     for test in ["float(huge)", "float(mhuge)",
  346.                  "complex(huge)", "complex(mhuge)",
  347.                  "complex(huge, 1)", "complex(mhuge, 1)",
  348.                  "complex(1, huge)", "complex(1, mhuge)",
  349.                  "1. + huge", "huge + 1.", "1. + mhuge", "mhuge + 1.",
  350.                  "1. - huge", "huge - 1.", "1. - mhuge", "mhuge - 1.",
  351.                  "1. * huge", "huge * 1.", "1. * mhuge", "mhuge * 1.",
  352.                  "1. // huge", "huge // 1.", "1. // mhuge", "mhuge // 1.",
  353.                  "1. / huge", "huge / 1.", "1. / mhuge", "mhuge / 1.",
  354.                  "1. ** huge", "huge ** 1.", "1. ** mhuge", "mhuge ** 1.",
  355.                  "math.sin(huge)", "math.sin(mhuge)",
  356.                  "math.sqrt(huge)", "math.sqrt(mhuge)", # should do better
  357.                  "math.floor(huge)", "math.floor(mhuge)"]:
  358.  
  359.         try:
  360.             eval(test, namespace)
  361.         except OverflowError:
  362.             pass
  363.         else:
  364.             raise TestFailed("expected OverflowError from %s" % test)
  365.  
  366. # ---------------------------------------------- test huge log and log10
  367.  
  368. def test_logs():
  369.     import math
  370.  
  371.     if verbose:
  372.         print "log and log10"
  373.  
  374.     LOG10E = math.log10(math.e)
  375.  
  376.     for exp in range(10) + [100, 1000, 10000]:
  377.         value = 10 ** exp
  378.         log10 = math.log10(value)
  379.         verify(fcmp(log10, exp) == 0)
  380.  
  381.         # log10(value) == exp, so log(value) == log10(value)/log10(e) ==
  382.         # exp/LOG10E
  383.         expected = exp / LOG10E
  384.         log = math.log(value)
  385.         verify(fcmp(log, expected) == 0)
  386.  
  387.     for bad in -(1L << 10000), -2L, 0L:
  388.         try:
  389.             math.log(bad)
  390.             raise TestFailed("expected ValueError from log(<= 0)")
  391.         except ValueError:
  392.             pass
  393.  
  394.         try:
  395.             math.log10(bad)
  396.             raise TestFailed("expected ValueError from log10(<= 0)")
  397.         except ValueError:
  398.             pass
  399.  
  400. # ---------------------------------------------------------------- do it
  401.  
  402. test_division()
  403. test_bitop_identities()
  404. test_format()
  405. test_misc()
  406. test_auto_overflow()
  407. test_float_overflow()
  408. test_logs()
  409.